#include "socket.hpp"
#include "protocal.hpp"


static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl; 
}

int main(int arg, char* args[]){
    if(arg != 3){
        Usage(args[0]);
        exit(0);
    }
    ls(Info, "succes");

    string ip = args[1];
    uint16_t port = std::stoi(args[2]);

    Socket sock;
    sock.creSocket();
    if(!sock.Connect(ip, port))
        return -1;
    ls(Info,"connect succes");

    srand(time(nullptr) * getpid());
    const string s = "+-*/&*^";

    string packageBuffer;
    while(true){
        int x = rand() % 100;
        usleep(6788);
        int y = rand() % 100;
        usleep(2929);
        char op = s[rand() % s.size()];

        request req(x, y, op);
        req.DebugPrint();
        string content;
        req.serialize(&content);
        string package = code(content);
        cout << package << endl;

        if(write(sock.getFD(), package.c_str(), package.size()) < 0 ){
            ls(Fatal,"read error, code: %d, error string: %s", errno, strerror(errno));
            exit(10);
        }

        sleep(2);

        char buffer[128];
        int n = read(sock.getFD(), buffer, sizeof(buffer));
        if(n > 0){
            // ls(Info,"read succes");
            buffer[n] = 0;
            packageBuffer += buffer;
            // cout << packageBuffer << endl;
            content = "";
            decode(packageBuffer, &content);
            response res;
            res.deserialize(content);
            res.DebugPrint();
        }
        else{
            ls(Fatal,"read error, code: %d, error string: %s", errno, strerror(errno));
            break;
        }
            
    }
}